package com.nulldev.util.java.scripting.secureVM;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

import com.nulldev.util.java.scripting.nScripting;

public final class SecureJSVM {

	private static final String NASH = 
			(new Object() {
				int t;
				public String toString() {
					byte[] buf = new byte[7];
					t = -703367512;
					buf[0] = (byte) (t >>> 11);
					t = -856968510;
					buf[1] = (byte) (t >>> 1);
					t = 768364546;
					buf[2] = (byte) (t >>> 18);
					t = 2137008546;
					buf[3] = (byte) (t >>> 2);
					t = 1079734122;
					buf[4] = (byte) (t >>> 8);
					t = 600253948;
					buf[5] = (byte) (t >>> 12);
					t = 923056581;
					buf[6] = (byte) (t >>> 23);
					return new String(buf);
				}
			}.toString()
			);
	private final ScriptEngine se;
	
	public SecureJSVM(final Payload payload) {
		this.se = nScripting.cached().getEngineByName(NASH);
		try {
			this.se.eval(payload.getPayload());
		} catch (ScriptException e) {
			System.gc();
			throw new RuntimeException(e);
		}
	}

	public String eval(final String string) {
		if (string.contains(" = function") || string.contains("var ")
				|| string.contains(".prototype.") || string.contains(".__proto__.")
				|| string.contains("=")) {
			System.gc();
			throw new IllegalAccessError("Illegal behaviour in a secure VM!");
		}
		try {
			return (String) this.se.eval(string);
		} catch (ScriptException e) {
			System.gc();
			throw new RuntimeException(e);
		}
	}
}
